<?php
namespace App\Api\Fcjd;

use PhalApi\Api;


/**
 * 非常检单更新APP信息
 * @author dogstar 20200331
 */
class UpdateInfo extends Api {
    public function getRules() {
        return array(
            'app' => array(
                'oaid' => array('name' => 'oaid', 'type' => 'string', 'require' => true, 'desc' => '设备唯一标识'),
                'app_name' => array('name' => 'app_name', 'type' => 'string', 'require' => true, 'desc' => 'app_name'),
                'install' => array('name' => 'install', 'type' => 'string', 'require' => false, 'desc' => 'install'),
                'is_reg' => array('name' => 'is_reg',  'require' => false, 'desc' => 'is_reg'),
                'is_ban' => array('name' => 'is_ban',  'require' => false, 'desc' => 'is_ban'),
                'data' => array('name' => 'data',  'require' => true, 'desc' => 'data'),
            ),
        );
    }

    /**
     * 更新app信息
     * @desc 更新app信息
     * @return int res 更新app信息
     */
    public function app() {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        // 获取缓存实例
        $cache = \PhalApi\DI()->cache;
        // 生成缓存键
        $cacheKey = 'oaid_upload_' . $this->oaid;
        // 检查缓存是否存在
        if ($cache->get($cacheKey)) {
            // 缓存存在，直接返回，中止本次上传
            return array(
                'success' => false,
                'msg' => '上传过于频繁，请稍后再试',
                'data' => null
            );
        }
        // 设置缓存，有效期 1 分钟
        $cache->set($cacheKey, true, 60);

        // $json = json_decode($this->data, true);
        $data = array(
            'oaid' => $this->oaid,
            'app_name' => $this->app_name,
            'install' => $this->install,
            'is_reg' => $this->is_reg,
            'is_ban' => $this->is_ban,
            'apptodo' => $this->data
        );

        $save = array();
        foreach ($data as $key => $value) {
            if ($value) {
                $save[$key] = $value;
            }
        }
        $save['update_time'] = date("Y-m-d H:i:s", time());
        \PhalApi\DI()->response->setMsg('success');
        
        // 获取设备信息
        $appId = \PhalApi\DI()->notorm->phone_app->where('name', $this->app_name)->fetchOne();
        $device = \PhalApi\DI()->notorm->phone_list->where('oaid', $this->oaid)->fetchOne();

        // 获取设备的任务列表并转为数组
        $taskArray = explode(',', $device['task']);
        // 获取当前appId在任务列表中的位置
        $currentIndex = array_search($appId['id'], $taskArray);
        // 如果找到当前appId
        if ($currentIndex !== false) {
            // 如果是最后一个任务,则返回第一个任务
            if ($currentIndex == count($taskArray) - 1) {
                $task_n = $taskArray[0];
            } else {
                // 否则返回下一个任务
                $task_n = $taskArray[$currentIndex + 1];
            }
        } else {
            // 如果没找到当前appId,则默认返回第一个任务
            $task_n = $taskArray[0];
        }

        $updateData = array(
            'ip' => $_SERVER['REMOTE_ADDR'],
            'task_n' => $task_n, 
            'update_time' => date("Y-m-d H:i:s", time())
        );

        //对当前任务，进行下移一位操作
        \PhalApi\DI()
            ->notorm
            ->phone_list
            ->where('oaid', $this->oaid)
            ->update($updateData);


        //处理phone_app_info待更新的数据
        $mobileByDevice = $device['mobile'];
        $phoneAppInfoData = \PhalApi\DI()
                                ->notorm
                                ->phone_app_info
                                ->select('*')
                                ->where(
                                    array( 
                                        'app_name' => $this->app_name, 
                                        'mobile' => $mobileByDevice 
                                    )
                                )
                                ->fetchOne();

        $apptodoBySelect = json_decode($phoneAppInfoData['apptodo'], true);
 
        $dateBySelect = $phoneAppInfoData['date'];
        $sysDate = date("Y-m-d", time());

        // return [$device, $phoneAppInfoData, $sysDate, $dateBySelect];
        $yGoldBySelect = $phoneAppInfoData['yesterday_gold'];
        $byGoldBySelect = $phoneAppInfoData['before_yesterday_gold'];
        $goldBySelect = isset($apptodoBySelect['gold']) ? $apptodoBySelect['gold'] : null;
 
        if($dateBySelect != $sysDate){
            $save['before_yesterday_gold'] = $yGoldBySelect;
            $save['yesterday_gold'] = $goldBySelect;
        }
 
        $save['name'] = $device['name'];
        $save['mobile'] = $device['mobile'];
        $save['username'] = $device['username'];
        $save['mun'] = $device['mun'];
        $save['date'] = date("Y-m-d", time());
 
         //改为按手机号 处理上报内容, 这样方便更换了设备后的数据, 避免出现手机号对应多个oaid的情况
        $where = array(
            'mobile' => $device['mobile'],
            'app_name' => $this->app_name,
        );
 
        $res = \PhalApi\DI()->notorm->phone_app_info->where($where)->update($save);
        if($res){
            return $res;
        }
        
        return \PhalApi\DI()->notorm->phone_app_info->insert($save);
    }
}

